const fs = require('fs');
const path = require('path');
const logger = require('@utils/logger');

async function findMaxNumberInDirectory(directoryPath) {
    try {
        // 获取目录下所有文件和子目录
        const files = await fs.promises.readdir(directoryPath);
        let maxNumber = 0;
        const pattern = /\[\+(\d+)\]/g; // 匹配[+数字]的正则表达式

        // console.log('检测文件：：', files);
        // 遍历每个文件/目录
        for (const file of files) {
            const filePath = path.join(directoryPath, file);
            const stats = await fs.promises.stat(filePath);

            // logger.info('xorz!');

            if (stats.isDirectory()) {
                // 如果是目录，递归处理
                const subDirMax = await findMaxNumberInDirectory(filePath);
                if (subDirMax > maxNumber) {
                    maxNumber = subDirMax;
                }
            } else if (stats.isFile() && /\.(js|txt)$/i.test(file)) {
                // 只处理文件（不包括目录）且是文本文件（js、txt等）
                const content = await fs.promises.readFile(filePath, 'utf-8');
                const lines = content.split('\n');

                // 检查每一行
                for (const line of lines) {
                    // logger.warn(`【${line}】`);
                    let match;
                    while ((match = pattern.exec(line)) !== null) {
                        // console.log('匹配到：：', line);
                        const number = parseInt(match[1], 10);
                        if (number > maxNumber) {
                            maxNumber = number;
                        }
                    }
                }
            }
        }

        return maxNumber === 0 ? null : maxNumber;
    } catch (error) {
        console.error('Error processing directory:', error);
        return null;
    }
}

function maxSort(topath) {
    findMaxNumberInDirectory(topath)
        .then(maxNumber => {
            if (maxNumber !== null) {
                console.error(`The maximum number found is: ${maxNumber}, the next SN is ${maxNumber + 1}`);
            } else {
                console.error('No matching pattern found in any files.');
            }
        });
}

module.exports = {
    maxSort
}